﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace 舒尔特方格生成器
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        public class ListShuffler
        {
            private static Random _random = new Random();

            public static void Shuffle<T>(List<T> list)
            {
                int n = list.Count;
                while (n > 1)
                {
                    n--;
                    int k = _random.Next(n + 1);
                    T value = list[k];
                    list[k] = list[n];
                    list[n] = value;
                }
            }
        }

        private void btnCreate_Click(object sender, RoutedEventArgs e)
        {
            var rows = cmbRowsCount.SelectedIndex + 4;
            var cols = cmbColumnsCount.SelectedIndex + 4;

            childGrid.Children.Clear();

            childGrid.ColumnDefinitions.Clear();
            childGrid.RowDefinitions.Clear();

            for (int r = 0; r < rows; r++)
            {
                childGrid.RowDefinitions.Add(new RowDefinition());
            }

            for (int c = 0; c < cols; c++)
            {
                childGrid.ColumnDefinitions.Add(new ColumnDefinition());
            }

            var range = cols * rows;

            var list = new List<int>();
            for (int i = 1; i <= range; i++)
            {
                list.Add(i);
            }

            ListShuffler.Shuffle(list);

            var margin = new Thickness(15);

            if (range >= 10 && range < 100)
            {
                margin = new Thickness(10);
            }
            else if (range >= 100)
            {
                margin = new Thickness(5);
            }

            for (int r = 1; r <= rows; r++)
            {
                for (int c = 1; c <= cols; c++)
                {
                    var index = (r - 1) * cols + c - 1;
                    var vb = new Viewbox() { Margin = margin, };
                    var tb = new TextBlock()
                    {
                        HorizontalAlignment = HorizontalAlignment.Center,
                        VerticalAlignment = VerticalAlignment.Center,
                    };
                    // tb.Text = list[index - 1].ToString();
                    var num = list[index].ToString();
                    var preSpan = new System.Windows.Documents.Span();

                    if (ckxShowZero.IsChecked == true)
                    {
                        preSpan.Foreground = Brushes.Black;
                    }
                    else
                    {
                        preSpan.Foreground = Brushes.Transparent;
                    }

                    if (range >= 10 && range < 100 && num.Length < 2)
                    {
                        preSpan.Inlines.Add(new Run("0"));
                    }
                    else if (range >= 100)
                    {
                        if (num.Length == 1)
                        {
                            preSpan.Inlines.Add(new Run("00"));
                        }
                        else if (num.Length == 2)
                        {
                            preSpan.Inlines.Add(new Run("0"));
                        }
                    }
                    tb.Inlines.Add(preSpan);
                    var numSpan = new Span() { Foreground = Brushes.Black, };
                    numSpan.Inlines.Add(new Run(num));
                    tb.Inlines.Add(numSpan);
                    vb.Child = tb;
                    childGrid.Children.Add(vb);
                    Grid.SetColumn(vb, c - 1);
                    Grid.SetRow(vb, r - 1);
                }
            }
        }

        public RenderTargetBitmap GetRenderTargetBitmap(bool highQuality = true)
        {
            RenderTargetBitmap rtb;

            if (highQuality)
            {
                rtb = new RenderTargetBitmap(
                    (int)(mainBorder.ActualWidth * 3.125 * 2 + 1),
                    (int)(mainBorder.ActualHeight * 3.125 * 2 + 1),
                    600, 600, PixelFormats.Pbgra32);
                //300÷96=3.125//用来打印的图片分辨率要高些。96DPI只适合屏幕显示。
            }
            else
            {
                rtb = new RenderTargetBitmap(
                    (int)(mainBorder.ActualWidth),
                    (int)(mainBorder.ActualHeight),
                    96, 96, PixelFormats.Pbgra32);//只在屏幕上显示的图片分辨率可以低些，96DPI就够了。
            }

            mainBorder.Arrange(new System.Windows.Rect(0, 0, mainBorder.ActualWidth, mainBorder.ActualHeight));// 设置渲染位置和大小

            rtb.Render(mainBorder);
            return rtb;
        }


        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            RenderTargetBitmap rtb;

            string filename;

            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Title = "舒尔特方格生成器";
            sfd.Filter = "标记图像格式(*.tif)|*.tif|可移植网络图形(*.png)|*.png";
            sfd.FileName = $"[{childGrid.RowDefinitions.Count}x{childGrid.ColumnDefinitions.Count}]舒尔特方格 - " + DateTime.Now.ToShortDateString().Replace("/", "-") + " " + DateTime.Now.ToShortTimeString().Replace(":", "-");

            if (sfd.ShowDialog() != true) return;

            filename = sfd.FileName;

            bool isPng = filename.EndsWith(".png");

            try
            {
                BitmapEncoder encoder;

                if (isPng)
                {
                    rtb = GetRenderTargetBitmap(false);   // 96DPI
                    encoder = new PngBitmapEncoder();
                }
                else
                {
                    rtb = GetRenderTargetBitmap();        // 600DPI
                    encoder = new TiffBitmapEncoder();
                }

                encoder.Frames.Add(BitmapFrame.Create(rtb));
                using (Stream stm = File.Create(filename))
                {
                    encoder.Save(stm);
                }

                MessageBox.Show("[auto]已导出为：" + filename + "。", "舒尔特方格生成器");
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出为图像文件时出现异常。异常信息如下：\r\n"
                    + ex.Message + "\r\n" + ex.StackTrace, "舒尔特方格生成器");
            }
        }
    }
}
